package com.oncliedisk.administrator.Base;

import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.R;
import com.oncliedisk.administrator.DB.Dao;
import com.oncliedisk.administrator.adapter.FileAdapter;
import com.oncliedisk.administrator.content.FileConfig;
import com.oncliedisk.administrator.model.FileModel;

import com.oncliedisk.administrator.utils.FileUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/10.
 */
public class BaseActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    protected boolean isMulChoice = false; //是否多选
    protected List<FileModel> selectid = new ArrayList<>();
    protected LinearLayout showLongLayout; //下面的工具栏
    protected FileAdapter adapter; //适配器
    protected ListView listView; // ListView
    private TextView mTitle; //标题
    private ImageView mBack; //返回
    private RelativeLayout layout_title; //标题布局
    private RelativeLayout layout_num; //选中个数布局
    private TextView selecedNumber; //选中的个数
    private int selecedIndex; //选中个数
    private int currSelseNum; //当前选中了几个
    private ImageView openFile_img; //打开文件图标
    private TextView openFile_txt; //打开文件文字
    private int[] img_grey = {R.drawable.open_grey, R.drawable.down_grey, R.drawable.delete_grey, R.drawable.more_grey};
    private int[] img_white = {R.drawable.open_white, R.drawable.down_white, R.drawable.delete_white, R.drawable.more_white};
    private boolean isAllSeleced =false; //全选状态
    private PopupWindow window;
    private AlertDialog alertDialog; //重命名
    private  EditText  newFileNmae;
    private String currId = FileConfig.IS_ROOT; //当前ID
    private String currPosition = "0";
    private String paths = "网盘"; //路径
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        initWeight();
        initListener();
    }

    public void initAdapter(List<FileModel> data) {
        adapter = new FileAdapter(data, getActivity());
    }

    private void initListener() {
        findViewById(R.id.base_open).setOnClickListener(this);
        findViewById(R.id.base_delete).setOnClickListener(this);
        findViewById(R.id.base_down).setOnClickListener(this);
        findViewById(R.id.base_more).setOnClickListener(this);
        mBack.setOnClickListener(this);
        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);
        for (int i = 0; i < layout_num.getChildCount(); i++) {
            layout_num.getChildAt(i).setOnClickListener(this);
        }
    }

    private void initWeight() {
        showLongLayout = (LinearLayout) findViewById(R.id.base_layout);
        listView = (ListView) findViewById(R.id.base_listview);
        mTitle = (TextView) findViewById(R.id.base_title);
        mBack = (ImageView) findViewById(R.id.base_back);
        layout_title = (RelativeLayout) findViewById(R.id.base_layout_title);
        layout_num = (RelativeLayout) findViewById(R.id.base_layout_num);
        selecedNumber = (TextView) findViewById(R.id.base_selenum);
        LinearLayout open_layout = (LinearLayout) showLongLayout.getChildAt(0);
        openFile_img = (ImageView) open_layout.getChildAt(0);
        openFile_txt = (TextView) open_layout.getChildAt(1);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        mTitle.setText(title);
    }

    public boolean getOnItemLongClick(int position) {

        if (isMulChoice == false) {
            //如果现在不是长按状态,则进行长按操作
            List<FileModel> data = adapter.getData();
            //把所有条目的对象都设置成等待选中状态
            for (FileModel model : data) {
                model.setIsCheck(false);
                model.setIsLoading(false);
                model.setIsSingle(false);
                model.setIsLoading(true);
            }
            //把当前长按的这个条目设置为选中状态
            data.get(position).setIsCheck(true);
            updateAdapter();
            isMulChoice = true;
            //设置长按界面开启
            showLongLayout.setVisibility(View.VISIBLE);
            layout_num.setVisibility(View.VISIBLE);
            layout_title.setVisibility(View.GONE);
            return true;
        }
        return false;
    }

    /**
     * 执行点击事件
     *
     * @param position
     */
    public void getOnItemClick(int position) {
        FileModel item = (FileModel) adapter.getItem(position);
        if (isMulChoice == true) {
            //如果现在是长按状态,则点击的这个设置成选中状态
            item.setIsCheck(!item.isCheck());
            updateAdapter();
            return;
        }
        //点击文件夹
        int type = item.getType();
        if (type == FileConfig.TYPE_FOLDER) {
            //如果是文件夹,则打开文件夹
            adapter = new FileAdapter(Dao.getInstance(getActivity()).getFileById(item.getId()), getActivity());
            listView.setAdapter(adapter);
            currId = currId + "/" + String.valueOf(item.getId());
            currPosition = currPosition + "/" + position;
            paths += "/" + item.getName();
//            tv_path.setText(paths);
        } else {
            Toast.makeText(getActivity(), "打开文件", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新适配器
     */
    private void updateAdapter() {
        selectid.clear();
        adapter.notifyDataSetChanged();
        int selecedIndex = 0;
        for (FileModel model : adapter.getData()) {
            if (model.isCheck()) {
                selecedIndex++;
                selectid.add(model);
            }
        }
        selecedNumber.setText("已选中" + selecedIndex + "个");
        currSelseNum = selecedIndex;
        for (int i = 0; i < showLongLayout.getChildCount(); i++) {
            LinearLayout childAt = (LinearLayout) showLongLayout.getChildAt(i);
            ImageView img = (ImageView) childAt.getChildAt(0);
            TextView txt = (TextView) childAt.getChildAt(1);
            img.setImageResource(selecedIndex >= 1 ? img_white[i] : img_grey[i]);
            txt.setTextColor(selecedIndex >= 1 ? getResources().getColor(R.color.white) : getResources().getColor(R.color.grey));
        }
        if (selecedIndex > 1) {
            openFile_img.setImageDrawable(getResources().getDrawable(R.drawable.open_grey));
            openFile_txt.setTextColor(getResources().getColor(R.color.grey));
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.base_open:
                //打开文件
                if(selectid.size() == 1){
                    //只有选中的等于1，才可以打开文件
                    openFile();
                }
                break;

            case R.id.base_delete:
                //删除文件
                if(selectid.size() > 0){
                    //删除文件必须选中的文件大于0
                    deleteFile();
                }
                break;

            case R.id.base_down:
                if(selectid.size() > 0){
                   downLoad();
                }
                break;

            case R.id.base_more:
                //更多文件
                if(selectid.size() > 0){
                    openMoreFIle();
                }
                break;

            case R.id.base_back:
                //返回键
                finish();
                break;

            case R.id.base_cancel:
                //取消多选
                cancelLongClick();
                break;

            case R.id.base_allseleced:
                //全选
                selecedAll();
                break;

            case R.id.more_move:
                //移动文件
               moveFile();
                break;

            case R.id.more_rename:
                //重命名
                reName();
                break;

            case R.id.dialog_yes:
                //点击确定修改名字
                updateName();
                break;

            case R.id.dialog_cancel:
                //点击取消修改名字
                alertDialog.dismiss();
                break;

        }
    }

    private void updateName() {
        FileModel fileModel = selectid.get(0);
        Dao.getInstance(getActivity()).updateName(fileModel.getId(), fileModel.getType(), newFileNmae.getText().toString());
        for(FileModel model : adapter.getData()){
            if(model.getId() == fileModel.getId()){
                model.setName(newFileNmae.getText().toString());
            }
        }
        updateAdapter();
        cancelLongClick();
        alertDialog.dismiss();
    }

    /**
     * 重命名
     */
    private void reName() {
        //只有选中一个的时候，才可以重命名
        if(selectid.size() == 1){
            openReName();
            window.dismiss();
        }
    }

    /**
     * 移动文件
     */
    private void moveFile() {
        Toast.makeText(getActivity(), "移动", Toast.LENGTH_SHORT).show();
    }

    /**
     * 选择所有或者取消所有
     */
    private void selecedAll() {
        for (FileModel model : adapter.getData()) {
            initModel(model);
            if (isAllSeleced) {
                model.setIsCheck(false);
                model.setIsLoading(true);
            } else {
                model.setIsLoading(false);
                model.setIsCheck(true);
            }
        }
        isAllSeleced = !isAllSeleced;
        updateAdapter();
    }

    /**
     * 打开更多选项
     */
    private void openMoreFIle() {
        openMore();
    }

    /**
     * 下载文件
     */
    private void downLoad() {
        Toast.makeText(getActivity(), "下载" + selectid.size() + "个", Toast.LENGTH_SHORT).show();
    }

    /**
     * 删除文件
     */
    private void deleteFile() {
        if (isMulChoice == true) {
            isMulChoice = false;
            adapter.getData().removeAll(selectid);
            Dao.getInstance(getActivity()).deleteModel(selectid);
            // 将数据从list中移除
            cancelLongClick();
        }
    }

    /**
     * 打开文件
     */
    private void openFile() {
        Toast.makeText(getActivity(), "打开文件", Toast.LENGTH_SHORT).show();
    }

    /**
     * 打开重命名窗口
     */
    private void openReName() {
        //初始化新建文件夹Dialog的控件
        View dialog_view = getActivity().getLayoutInflater().inflate(R.layout.item_dialog_rename, null);
        Button newFileNo = (Button) dialog_view.findViewById(R.id.dialog_cancel);
        newFileNmae = (EditText) dialog_view.findViewById(R.id.dialog_name);
        Button newFileYes = (Button) dialog_view.findViewById(R.id.dialog_yes);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        FileModel fileModel = selectid.get(0);
        newFileNmae.setText(fileModel.getName());
        alertDialog = builder.create();
        alertDialog.setView(dialog_view);
        alertDialog.show();
        newFileYes.setOnClickListener(this);
        newFileNo.setOnClickListener(this);
    }

    /**
     * 打开更多
     */
    private void openMore() {
        window = new PopupWindow(getActivity().getResources().getDisplayMetrics().widthPixels / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = getActivity().getLayoutInflater().inflate(R.layout.item_pop_more, null);
        view.findViewById(R.id.more_move).setOnClickListener(this);
        view.findViewById(R.id.more_rename).setOnClickListener(this);
        ImageView more_img = (ImageView) view.findViewById(R.id.more_img);
        TextView more_tv = (TextView) view.findViewById(R.id.more_tv_rename);
        window.setContentView(view);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        int[] widthAndHeightforView = FileUtils.getWidthAndHeightforView(showLongLayout);
        window.showAtLocation(showLongLayout, Gravity.RIGHT | Gravity.BOTTOM, 0, widthAndHeightforView[1]);
        if(selectid.size() == 1){
            //说明只有选中一个，可以重命名操作
            more_img.setImageResource(R.mipmap.edit_tools_rename);
            more_tv.setTextColor(getResources().getColor(R.color.white));
        }else{
            more_img.setImageResource(R.mipmap.edit_tools_rename_disable);
            more_tv.setTextColor(getResources().getColor(R.color.disable));
        }
    }

    public Activity getActivity() {
        return this;
    }

    private void initModel(FileModel model) {
        model.setIsLoading(false);
        model.setIsCheck(false);
        model.setIsSingle(false);
    }

    /**
     * 退出长按事件
     */
    public void cancelLongClick() {
        List<FileModel> data = adapter.getData();
        for (FileModel model : data) {
            model.setIsSingle(true);
        }
        updateAdapter();
        isMulChoice = false;
        showLongLayout.setVisibility(View.GONE);
        layout_num.setVisibility(View.GONE);
        layout_title.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            //如果是长按
            if (isMulChoice == true) {
                isMulChoice = false;// 退出多选模式
                selectid.clear();
                initCheck();
                // 重新加载Adapter
                adapter.notifyDataSetChanged();
                showLongLayout.setVisibility(View.GONE);
                layout_num.setVisibility(View.GONE);
                layout_title.setVisibility(View.VISIBLE);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initCheck() {
        for (FileModel item : adapter.getData()) {
            item.setIsCheck(false);
            item.setIsLoading(false);
            item.setIsSingle(true);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        getOnItemClick(position);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
        return getOnItemLongClick(position);
    }
}
